package greatwall.myreader;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import com.iximo.domain.Book;
import com.iximo.openAPI.impl.IximoOpenAPIGetImpl;
import com.iximo.util.OpenAPIClient;
import greatwall.myreader.OpenAPIClientFactory;
import greatwall.myreader.R;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

public class ShowSearchBookList extends Activity
{
	private TextView TVResult;

	private ProgressDialog progressDialog;
	private IximoOpenAPIGetImpl Get = new IximoOpenAPIGetImpl();
	private ArrayList<HashMap<String,Object > > listItem = null;
	private String searchContent;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.searchbookmain);
        searchContent = getIntent().getExtras().getString("searchcontent");
        GetControls();
        GetSearchResult();
    }
   
    private void GetControls()
    {
    	TVResult = (TextView)findViewById(R.id.resultContent);

    }
    
    private OpenAPIClient XiMoClient = OpenAPIClientFactory.GetInstance();
    
    public void GetSearchResult() {
		// TODO Auto-generated method stub
		//开启progressDialog，显示等待框
		progressDialog = ProgressDialog.show(ShowSearchBookList.this, 
				"Loading...", "Please wait...", true, false);  
		//启动线程获取图书信息
		new Thread(){
			@Override
			public void run()
			{						
				try
				{
					//获取113277那本书的信息,并将标题封装成Message传送给Handler处理
				    String content = XiMoClient.search("title", searchContent, "");
					Message msg = new Message();
					Bundle b = new Bundle();
					b.putString("bookinfo",content);
					msg.setData(b);
					handler.sendMessage(msg);
					
				}
				catch(Exception e)
				{
					//没有获取到，发送异常消息
					Message msg = new Message();
					Bundle b = new Bundle();
					b.putString("bookinfo", "获取失败");
					msg.setData(b);
					handler.sendMessage(msg);
				}
			}
		}.start();
	}
	
    
	//处理线程发送过来的消息
    private Handler handler = new Handler(){
    	@Override
    	public void handleMessage(Message msg)
    	{
			try 
			{
				String tempResult = msg.getData().getString("bookinfo");
				InputStream inputStream = new ByteArrayInputStream(tempResult.getBytes());
				List<Book> bookListByNumData = Get.getBookByNumData(inputStream);
				ListView list = (ListView) findViewById(R.id.ListView01);
		         //生成动态数组，加入数据   
		        listItem = new ArrayList<HashMap<String, Object>>();
				for(int i=0;i<bookListByNumData.size();i++)   
		        {   
		            HashMap<String, Object> map = new HashMap<String, Object>();     
//		            map.put("ItemImage", BitmapFactory.decodeFile(bookListByNumData.get(i).getLimageURL()));//图像资源的ID
      	            map.put("ItemImage",R.drawable.book_bg_shadow);
		            map.put("BookName","书名：" + bookListByNumData.get(i).getTitle());   
		            map.put("Writer","作者：" +  bookListByNumData.get(i).getAuthor());
		            map.put("Visitor", "人气：" + bookListByNumData.get(i).getHitCount());
		            map.put("Size", "字数：" + bookListByNumData.get(i).getWords());
		            map.put("Classification", "所属分类： " + bookListByNumData.get(i).getCategoryName());
		            map.put("CategoryID", bookListByNumData.get(i).getBookID());
		            listItem.add(map);   
		        }   
		        //生成适配器的Item和动态数组对应的元素   
		        SimpleAdapter listItemAdapter = new SimpleAdapter(ShowSearchBookList.this,listItem,//数据源    
		            R.layout.searchbookuser,//ListItem的XML实现   
		            //动态数组与ImageItem对应的子项           
		            new String[] {"ItemImage","BookName", "Writer","Visitor","Size","Classification"},    
		            //ImageItem的XML文件中的一张图片和三个TextView ID   
		            new int[] {R.id.ItemImage,R.id.BookName,R.id.Writer,R.id.Visitor,R.id.Size,R.id.Classification}   
		        );   
		          
		        //添加并且显示   
		        list.setAdapter(listItemAdapter);
		        list.setOnItemClickListener(ListItemListener);
		        progressDialog.dismiss();
			} catch (Exception e) 
			{
				// TODO Auto-generated catch block
				progressDialog.dismiss();				
			}
			
    	}
    };
    private OnItemClickListener ListItemListener = new OnItemClickListener()
    {

		@Override
		public void onItemClick(AdapterView<?> arg0,View arg1, int arg2,long arg3) 
		{

				
			//Log.i("1",listItem.get((int)arg3).get("CategoryID").toString());
			Intent intent = new Intent();
			Log.i("num", arg3 + "");
			intent.putExtra("getString",listItem.get((int)arg3).get("CategoryID").toString());
		    
		    intent.setClass(ShowSearchBookList.this,Book_Detail_info.class);
		    
		    startActivity(intent);				

	}
    	
 };
}
